#! /bin/bash
# 接收1个参数：$1（all:重启所有，fe只重启前端，ng只重启nginx，be只重启后端）
# shell语法需注意：赋值语句的"="前后一定不要有空格，if语句的"="前后一定要有空格
result=""
cd ~/project/RuoYi-Vue/
if [ $1 ]; then
  if [ $1 != "fe" ] && [ $1 != "be" ] && [ $1 != "ng" ] && [ $1 != "all" ]; then
      echo "参数错误(fe,ng,be,all)"
      exit -1
  fi
  if [ $1 = "be" ] || [ $1 = "all" ]; then
    # 第一种写法
    processPid=`ps -ef | grep ruoyi-admin.jar | grep -v grep | awk '{print $2}' | head -1`
    # 第二种写法
    # processPid=`ps -ef | grep ruoyi-admin.jar | grep -v grep | awk 'NR==1 {print $2}'`
    # 即使进程id不存在的时候，processPid数据类型也是integer，这种情况默认赋值0以解决下面gt操作，不然会报错
    processPid=${processPid:=0}
    if [ $processPid -gt 0 ];then
      kill -9 $processPid
    else
       echo "java进程不存在，无需kill"
    fi
    /opt/maven/apache-maven-3.6.3/bin/mvn clean install -DskipTests
    if [ $? -ne 0 ]; then
        result=$result"mvn install失败... "
    else
      # springboot自带的tomcat和websocket冲突，需要跳过tests
      /opt/maven/apache-maven-3.6.3/bin/mvn package -DskipTests
      if [ $? -ne 0 ]; then
          result=$result"mvn package失败... "
      else
        # BUILD_ID赋值什么内容均可，目的是改变BUILD_ID，因为Jenkins部署完毕会根据BUILD_ID去kill部署过程中产生的衍生进程，改变之后就找不到了，衍生进程也就保留了下来，从而解决了Jenkins部署服务无法启动的问题
        BUILD_ID=dontKillMe
        # Jenkins部署的时候，并不会自动输出到nohup.out，故需要重定向输出日志文件；2>&1代表将标准错误重定向到标准输出（0:stdin标准输入、1:stdout标准输出、2:stderr标准错误）
        nohup java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar ~/project/RuoYi-Vue/ruoyi-admin/target/ruoyi-admin.jar > ~/project/RuoYi-Vue/nohup.out 2>&1 &
        if [ $? -ne 0 ]; then
            result=$result"代码启动失败... "
        fi
      fi
    fi
  fi
  if [ $1 = "ng" ] || [ $1 = "all" ]; then
    cp -f ~/project/RuoYi-Vue/nginx.conf /usr/local/nginx/conf/nginx.conf
    if [ $? -eq 0 ]; then
      /usr/local/nginx/sbin/nginx -s reload
      if [ $? -ne 0 ]; then
        result=$result"nginx.conf语法错误... "
      fi
    else
      result=$result"nginx.conf文件复制失败... "
    fi
  fi
  if [ $1 = "fe" ] || [ $1 = "all" ]; then
    cd ~/project/RuoYi-Vue/ruoyi-ui
    npm install
    if [ $? -ne 0 ]; then
        result=$result"npm install失败... "
    else
      npm run build:prod
      if [ $? -ne 0 ]; then
        result=$result"npm build失败... "
      fi
    fi
  fi
  if [ $result=="" ]; then
    echo "执行成功！"
  else
    echo $result
  fi
else
  echo "请输入参数(fe,ng,be,all)"
fi
